package com.lych.server.service;

import com.lych.autoconfig.template.AipFaceTemplate;
import com.lych.autoconfig.template.OssTemplate;
import com.lych.dubbo.api.UserInfoApi;
import com.lych.model.domain.UserInfo;
import com.lych.model.vo.ErrorResult;
import com.lych.model.vo.UserInfoVo;
import com.lych.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 首次登录---补充头像
     * @param headPhoto
     * @param id
     */
    public void updatehead(MultipartFile headPhoto, Long id) throws IOException {
        //将头像上传到阿里云oss
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //调用百度云查看是否有人脸
        boolean detect = aipFaceTemplate.detect(imgUrl);
        //如果不包含，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
          //包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(imgUrl);
          userInfoApi.updatehead(userInfo);
        }
    }

    /**
     * 用户资料 - 读取
     * @param userID
     * @return
     */
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);

        UserInfoVo vo = new UserInfoVo();

        //copy同名同类型的属性
        BeanUtils.copyProperties(userInfo,vo);
        //因为类型不同，需要转换
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    /**
     * 更新用户资料
     * @param userInfo
     */
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.updateUserInfo(userInfo);
    }
}
